-- UICompass
-- Created by huanghr
-- 罗盘界面

UICompass = class("UICompass", function()
    return cc.Layer:create();
end);

function UICompass.create(classId)
    return UICompass.new(classId);
end

local MAX_OPTION_NUM    = 3;

-- 构造函数
function UICompass:ctor(classId)
    self:setName("UICompass");
    local node = cc.CSLoader:createNode("layout/dungeon/special/Compass.csb");
    self:addChild(node);
    self.node = node;

    self.classId = classId;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    self.compassInfo = ME.user.dbase:query("compass_info", {});

    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 事件响应
function UICompass:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UICompass 界面析构清理");
            EventMgr.removeAll("UICompass");
        end
    end);

    -- 注册学习职业成功的事件回调
    EventMgr.register("UICompass", event.COMPASS_BONUS, function(args)
        local bonus = args.bonus;

        showBonusNotifyForm(ItemM.query(self.classId, "name"), bonus);

        UIMgr.getCurrentScene():removeFormByName("UICompass");
    end);
end

-- 重绘
function UICompass:redraw()
    local classId = self.classId;
    local title, desc;
    title = ItemM.query(classId, "name");

    desc = getLocStr("compass_desc");

    local bonusList = self.compassInfo["bonus"];

    self.items = {};
    local itemName = {};

    for k, bonus in pairs(bonusList) do
        local name
        if bonus[1] == 2 then
            name = FieldsM.query(bonus[2], "name");
            self.items[k] = name;
            table.insert(itemName, name);
        elseif bonus[1] == 1 then
            name = ItemM.query(bonus[2], "name");
            self.items[k] = name;
            table.insert(itemName, name);
        end
    end

    -- 消耗
    local careerId = FormulaM.invoke("GET_COMPASS_CAREER_ID", classId);
    local times = self.compassInfo["times"] or 0;
    local cost = RiskerEquipM.queryCompass(careerId, 1 + times, "cost")[3];

    desc = string.format(desc, itemName[1], itemName[2], cost);

    -- 设置标题
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 正文样式
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    -- 绘制选项按钮
    self:redrawOptions();

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local nodeArr = table.append({ titleLabel, descLabel }, self.optionList);
    local offsetArr = { 40, 40, };

    for _, _ in ipairs(self.optionList) do
        table.insert(offsetArr, -10);
    end

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL, nodeArr, offsetArr);

    -- 根据适配后的界面高度比例，对界面上的角标位置进行修正
    local bg1 = findChildByName(self.node, "CT/sub_bg_l");
    local bg2 = findChildByName(self.node, "CT/sub_bg_r");

    local fixY, deltaY = math.modf(AlignM.BG_SIZE_NORMAL.height * bg:getScaleY() / 2);
    fixY = fixY - 25 * bg:getScaleY();

    bg1:setPositionY(fixY);
    bg2:setPositionY(fixY);

    -- 背景的icon
    local iconImg = findChildByName(self.node, "CT/icon");

    iconImg:loadTexture(getItemIconPath(ItemM.query(classId, "icon")));

    local scale = 1.5;

    iconImg:setScale(scale);
    iconImg:setOpacity(80);
    iconImg:setPositionY(descLabel:getPositionY());
end

-- 绘制选项按钮
function UICompass:redrawOptions()
    self.optionList = {};

    local options = table.keys(self.compassInfo["bonus"]);

    table.insert(options, -1);

    local optionBtn = findChildByName(self.node, "CT/option1");
    -- 根据配置，添加选项按钮
    for index, optionId in ipairs(options) do
        local button;
        if index == 1 then
            -- 第一个直接使用原先的option1
            button = optionBtn;
        else
            -- 其他的需要自己复制一个按钮出来
            button = optionBtn:clone();

            optionBtn:getParent():addChild(button);
        end

        -- 记录按钮的index和optionId
        button.index = index;
        button.optionId = optionId;

        -- 加入选项列表
        table.insert(self.optionList, button);

        -- 设置选项的文本
        TextStyleM.setTextStyle(button, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

        local text;
        if optionId == -1 then
            text = getLocStr("wait_next");
        else
            text = string.format(getLocStr("compass_collect_item"), self.items[optionId]);
        end

        button:setTitleText(text);

        -- 注册点击事件
        local function onButtonClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_return");

                -- 调用点击处理
                self:onClickOption(sender);
            end
        end
        button:addTouchEventListener(onButtonClick);
    end
end

-- 弹出失败提示语
function UICompass:doFailTip(optionId, reason)
    local tips;
    local failTip = SkyExploreTriggerM.queryOption(optionId, "fail_tip") or {};

    failTip = failTip[reason];
    -- 如果是字符串型的提示语配置，并且存在一样的公式时，认为是公式，调用公式获取提示语
    if type(failTip) == "string" and FormulaM.getFormula(failTip) then
        tips = FormulaM.invoke(failTip, self.triggerId, optionId, self.questionId);
    else
        tips = failTip;
    end

    if type(self.questionId) == "number" then
        tips = SkyExploreTriggerM.queryQuestion(self.questionId, "fail_tip");
        tips = getLocStr(tips);
    end

    if type(tips) == "string" then
        alert(tips);
    elseif type(tips) == "table" then
        for _, tipStr in ipairs(tips) do
            alert(tipStr);
        end
    end
end

-- 选项点击回调
function UICompass:onClickOption(button)
    local optionId;
    optionId = button.optionId;

    if optionId == -1 then
        AudioM.playFx("button_return");

        UIMgr.getCurrentScene():removeFormByName("UICompass");
    else
        local ret = RiskerEquipM.canTakeCompassBonus(self.classId);
        if ret == true then
            DungeonActionM.go("take_compass_bonus", self.classId, optionId);

            UIMgr.getCurrentScene():removeFormByName("UICompass");
        elseif type(ret) == "string" then
            alert(getLocStr(ret));
        end
    end
end

-- 注册点击事件
function UICompass:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            UIMgr.getCurrentScene():removeFormByName("UICompass");
        end
    end
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 黑色背景点击响应
    local bgNode = findChildByName(self.node, "bg/bgImg");
    bgNode:setTouchEnabled(true);
    bgNode:addTouchEventListener(onBackClick);
end

-- 适配
function UICompass:resize()
    local node = self.node;

    -- bg充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

